package com.hmdp.service.impl;

import cn.hutool.bloomfilter.BloomFilter;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.RedisCacheClient;
import com.hmdp.utils.RedisData;
import org.redisson.api.RBloomFilter;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constants.RedisConstants.*;
import static com.hmdp.constants.SystemConstants.DEFAULT_PAGE_SIZE;


@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisCacheClient redisCacheClient;

    private static final ExecutorService CHANE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //TODO 布隆过滤器
    @Resource
    private RBloomFilter<String> bloomFilter;


    @Override
    public Result queryShopById(Long id) {

        //缓存穿透
//         Shop shop = queryWithPassThrough(id);
        //缓存穿透 工具类
/*        Shop shop = redisCacheClient.queryWithPassThrough(
                CACHE_SHOP_KEY,
                id,
                Shop.class,
                this::getById,
                CACHE_SHOP_TTL,
                TimeUnit.MINUTES);*/

        //1-1、利用互斥锁解决缓存击穿(强一致)
//        Shop shop = queryWithMutex(id);
        //1-2、利用逻辑过期解决缓存击穿(最终一致)  工具类
/*        Shop shop = redisCacheClient.queryWithMutex(
                CACHE_SHOP_KEY,
                id,
                Shop.class,
                this::getById,
                LOCK_SHOP_KEY,
                CACHE_SHOP_TTL,
                TimeUnit.MINUTES);*/

        //2-1、利用逻辑过期解决缓存击穿(最终一致)
//        Shop shop = queryWithLogicalExpire(id);
        //2-2、利用逻辑过期解决缓存击穿(最终一致)  工具类
        Shop shop = redisCacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, LOCK_SHOP_KEY, CACHE_SHOP_TTL, TimeUnit.SECONDS);

        if (shop == null) {
            return Result.fail("店铺信息不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 存空字符解决缓存穿透
     *
     * @author Yhans
     * @date 2024/2/21 17:22
     */
    public Shop queryWithPassThrough(Long id) {

        String key = CACHE_SHOP_KEY + id;
        //1.从redis查询
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断redis中是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在 直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //3.判断是否为空字符串（缓存穿透）
        if ("".equals(shopJson)) {
            return null;
        }

        //4.查询数据库
        Shop dbShop = this.getById(id);
        //5.数据库 店铺不存在
        if (dbShop == null) {
            //缓存空值（缓存穿透）
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //6.数据库店铺存在 写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(dbShop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return dbShop;
    }

    /**
     * 布隆过滤器解决缓存穿透
     *
     * @author Yhans
     * @date 2024/2/28 13:07
     */
    public Shop queryWithPassThrough2(Long id) {

        // TODO 在查询之前使用布隆过滤器判断是否存在该 id
        if (!bloomFilter.contains(id.toString())) {
            // 说明数据库中肯定不存在该 id 对应的数据，直接返回null
            return null;
        }
        String key = CACHE_SHOP_KEY + id;
        //1.从redis查询
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断redis中是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在 直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //3.缓存未命中 查询数据库
        Shop dbShop = this.getById(id);
        //5.数据库 店铺不存在
        if (dbShop == null) {
            return null;
        }
        //6.数据库店铺存在 写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(dbShop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // TODO 将该 id 加入布隆过滤器
        bloomFilter.add(dbShop.getId().toString());
        return dbShop;
    }

    /**
     * 互斥锁解决缓存击穿
     *
     * @author Yhans
     * @date 2024/2/21 16:45
     */
    public Shop queryWithMutex(Long id) {

        String key = CACHE_SHOP_KEY + id;

        //1.从redis查询
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断redis中是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在 直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //3.判断是否为空字符串（缓存穿透）
        if ("".equals(shopJson)) {
            return null;
        }
        //实现缓存重建
        //获取互斥锁
        Shop dbShop = null;
        try {
            boolean isLock = tryLock(LOCK_SHOP_KEY + id);
            if (!isLock) {
                //获取锁失败
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //获取互斥锁成功
            //4.查询数据库
            dbShop = this.getById(id);
            //5.数据库 店铺不存在
            if (dbShop == null) {
                //缓存空值（缓存穿透）
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //6.数据库店铺存在 写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(dbShop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7.释放互斥锁
            unlock(LOCK_SHOP_KEY + id);
        }
        return dbShop;
    }

    /**
     * 逻辑过期解决缓存击穿
     *
     * @author Yhans
     * @date 2024/2/21 16:45
     */
    public Shop queryWithLogicalExpire(Long id) {
        //存在缓存预热  不需要考虑缓存穿透
        String key = CACHE_SHOP_KEY + id;

        //1.从redis查询
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2.判断是否命中热点key
        if (StrUtil.isBlank(shopJson)) {
            //3.未命中 直接返回
            return null;
        }
        //4.命中 需要判断过期时间
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);

        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期
            return shop;
        }
        //6.已过期 重建缓存
        boolean isLock = tryLock(LOCK_SHOP_KEY + id);
        //7.获取锁
        if (isLock) {
            //TODO 获取锁成功 开启独立线程 重建缓存(获取锁成功后，应再次检查缓存是否过期，因为可能获取的是前者释放的)
            CHANE_REBUILD_EXECUTOR.submit(() -> {
                //重建缓存
                try {
                    this.saveShop2Redis(id, 50L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(LOCK_SHOP_KEY + id);
                }
            });
        }
        //仍返回过期的数据
        return shop;
    }

    /**
     * 缓存预热
     *
     * @author Yhans
     * @date 2024/2/21 17:21
     */
    public void saveShop2Redis(Long id, Long seconds) throws InterruptedException {

        //查数据库
        Shop shop = this.getById(id);
        Thread.sleep(200L);     //200ms后预热成功
        LocalDateTime expireTime = LocalDateTime.now().plusSeconds(seconds);
        //封装逻辑过期时间
        RedisData redisData = new RedisData(shop, expireTime);

        //存入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result saveShop(Shop shop) {

        // 写入数据库
        this.save(shop);
        // 存入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + shop.getId(), JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return Result.ok(shop.getId());
    }

    /**
     * 新增根据地理坐分类查询商店信息
     *
     * @param typeId
     * @param current
     * @param x
     * @param y
     * @return Result
     * @author Yhans
     * @date 2024/2/27 15:34
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {

        //判断是否需要根据坐标查
        if (x == null || y == null) {
            //不需要坐标查询 ,按照数据库查询
            Page<Shop> page = this.query().eq("type_id", typeId).page(new Page<>(current, DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 计算分页参数
        int from = (current - 1) * DEFAULT_PAGE_SIZE;
        int end = current * DEFAULT_PAGE_SIZE;

        //使用redis 按照距离排序 分页分页查询
        // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(SHOP_GEO_KEY + typeId, GeoReference.fromCoordinate(x, y), new Distance(5000), RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));  //只能从0开始查询到end
        if (results == null) {
            return Result.ok();
        }
        // 解析id
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();

        if (list.size() <= from) {  //TODO 此时无法截取
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        //截取
        //list.subList(from, end);
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            //获取店铺id
            String shopId = result.getContent().getName();
            ids.add(Long.valueOf(shopId));
            //获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopId, distance);
        });
        //根据id批量查询shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            Distance distance = distanceMap.get(shop.getId().toString());
            shop.setDistance(distance.getValue());
        }

        return Result.ok(shops);
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {

        //采用删除缓存
        //先更新数据库，后删除redis
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        //1.更新数据库
        this.updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        //直接返回拆箱时 可能会出现空指针，
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

}
